<?php

namespace App\Models;

use App\Support\PDFLib;
use App\Support\Wechat\Exception;
use DB;
use Cache;

class Member extends BaseModel
{
    protected $table = "member";


    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 按条件查询单条数据
     */
    public function getOne(array $where, $fields = '*')
    {
        return $this->multiSelect($fields)->multiWhere($where)->first();
    }

    /**
     * 按条件查询全部数据,根据配置显示条数显示
     */
    public function getList(array $where = [], $fields = '*', $order = '', $pageSize = '')
    {
        if ($pageSize) {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->paginate($pageSize);
        } else {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->get();
        }
    }

    /**
     * 按条件查询全部数据,根据配置显示条数显示
     */
    public function getAllList(array $where = [], $fields = '*', $order = '', $pageSize = '')
    {
        if ($pageSize) {
            return $this->multiSelect($fields)->with('user')->with('card')->multiWhere($where)->multiOrder($order)->paginate($pageSize);
        } else {
            return $this->multiSelect($fields)->with('user')->with('card')->multiWhere($where)->multiOrder($order)->get();
        }
    }

    /**
     * 根据条件删除数据
     */
    public function del(array $where)
    {
        return $this->multiWhere($where)->delete();
    }

    /**
     *插入数据
     */
    public function add($data)
    {
//        dd($data);
        return $this->insertGetId($data);
    }

    /**
     *更新数据
     */
    public function up($where, $data)
    {
        return $this->multiWhere($where)->update($data);
    }

    /**
     * 获取和
     */
    public function getSum($where, $field)
    {
        return $this->multiWhere($where)->sum($field);
    }

    /**
     * 字段递加
     */
    public function inc($where, $field, $n)
    {
        return $this->multiWhere($where)->increment($field, $n);
    }

    public function card()
    {
        return $this->hasOne('App\Models\Card', 'member_id', 'id');
    }

    public function user()
    {
        return $this->belongsTo('App\Models\User', 'user_id', 'id');
    }

    public function getMemberInfoById($mid)
    {
        return $this->with('card')->with('user')->multiWhere(['id' => $mid])->first();
    }

    /**
     * 获取就诊人列表
     * @return mixed
     */
    public function getMyMemberList()
    {
        $uid = request('mid');
        $where['user_id'] = $uid;
        $order['id'] = 'DESC';
        $rows = $this->getList($where, '*', $order, 10);
        $Card = new Card();
        $user = new \App\Models\User();
        $user_info = $user->getUserById(array('id' => $uid));
        if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = getPageNoList($rows['last_page'], request('page', 1), 10);
        }

        foreach ($rows['data'] as $k => $v) {
            $c_where['user_id'] = $uid;
            $c_where['member_id'] = $v['id'];
            $rows['data'][$k]['hidelmobile'] = substr_replace($v['mobile'], '****', 3, 4);
            $rows['data'][$k]['hidelid_card'] = substr_replace($v['id_card'], '****', 5, 8);
            $rows['data'][$k]['has_card'] = 0;
            $c_info = $Card->getOne($c_where);
            $rows['data'][$k]['has_card'] = 0;
            if ($c_info) {
                if ($user_info['data']['primary_card_no'] == $c_info['card_no']) {
                    $rows['data'][$k]['card_num'] = 1;
                }
                if ($user_info['data']['second_card_no'] == $c_info['card_no']) {
                    $rows['data'][$k]['card_num'] = 2;
                }
                if ($user_info['data']['three_card_no'] == $c_info['card_no']) {
                    $rows['data'][$k]['card_num'] = 3;
                }
                $rows['data'][$k]['card'] = $c_info['card_no'];
                $rows['data'][$k]['is_loss'] = $c_info['status'];
                $rows['data'][$k]['has_card'] = 1;
            }
        }
        $rows['av_add'] = 1;
        if (count($rows['data']) >= 6) {
            $rows['av_add'] = 0;
        }
        return $rows;
    }

    /**
     * 获取就诊人列表
     * @return mixed
     */
    public function getMemberList()
    {
        $uid = request('mid');
        $where['uid'] = $uid;
        $order['id'] = 'desc';
        $rows = $this->getList($where, '*', $order, 10);
        if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = getPageNoList($rows['last_page'], request('page', 1), 10);
        }
        return $rows;
    }

    /**
     * @return mixed
     * 获取就诊人列表2
     */

    public function getMemberList2($request)
    {
        $where = [];
        if ($request['keywords']) {
            if (is_numeric($request['keywords'])) {
                $where['id'] = $request['keywords'];
            } else {
                $where['name'] = ['like', '%' . $request['keywords'] . '%'];
            }
        }


        if ($request['g_id'] != 0) {
            $u_where['group_id'] = $request['g_id'];
            $user = new User();
            $userlist = $user->getList($u_where);
            $userarr = [];
            foreach($userlist as $v){
                 $userarr[] = $v['id'];
            }
            $where['user_id'] = ['in',$userarr];
        }
        if ($request['starttime'] && $request['endtime']) {
            $where['created_at'] = ['glt', [['>', $request['starttime']], ['<=', $request['endtime']]]];;
        }
        $order['id'] = 'desc';
        $rows = $this->getAllList($where, '*', $order, 15);
        if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = getPageNoList($rows['last_page'], request('page', 1), 5);
        }
        return $rows;
    }

    /**
     * 添加就诊人
     * @param $request
     * @return array
     */

    public function addMember($request)
    {
        $uid = $request['mid'];
        $mobile = $request['mobile'];
        $relation = $request['relation'];
        $Sms = new SmsLog();
        $res = $Sms->checkSmsCaptcha($request);
        if ($res['state']==0) {
            return $res;
        }

        $mwhere['mobile'] = $mobile;
        $mwhere['name'] = $request['name'];
        $member = $this->getOne($mwhere);
        if($member){
            $res = ['state' => 0, 'msg' => "该就诊人已存在"];
            return $res;
        }

        $where['id'] = $uid;
        $user = new \App\Models\User();
        $res = $user->getOne($where)->toArray();
        // 判断添加就诊人是否到上限
        if ($res['member_count'] >= 6) {
            $res = ['state' => 0, 'msg' => '就诊人已到上限'];
            return $res;
        }
        // 验证手机格式
        $telReg = "/^1[3|4|5|7|8][0-9]{9}$/";
        if (!preg_match($telReg, $mobile, $arr)) {
            $res = ['state' => 0, 'msg' => "手机号格式不正确"];
            return $res;
        }
        $age = date('Y', time()) - date('Y', strtotime($request['birthday']));
        $data['user_id'] = $uid;
        $data['name'] = $request['name'];
        $data['sex'] = $request['sex'];
        $data['birthday'] = $request['birthday'];
        $data['relation'] = $relation;
        $data['mobile'] = $mobile;
        $data['created_at'] = date('Y-m-d H:i:s', time());
        // 查询his接口中是否存在该用户
        $his_get_user = apiCurl('getUser', array('cardno' => $mobile, 'name' => $request['name']));
        if (!empty($his_get_user['SCA01'])) {
            $his_id = $his_get_user['SCA01'];
        } else {
            $his_reg = apiCurl('userReg', array('openid' => $res['openid'], 'name' => $request['name'], 'sex' => $request['sex'], 'age' => $age, 'mobile' => $request['mobile'], 'id_card' => " "));
            if ($his_reg['Result']) {
                $his_id = $his_reg['SCA01'];
            }
        }
        if ($his_id) {
            $data['reffer_id'] = $his_id;
            $mid = $this->add($data);
            if (!$mid) {
                $res = ['state' => 0, 'msg' => '添加就诊人失败'];
                return $res;
            }
        }
        $sms = new SmsLog();
        //短信类型:1预约成功,2绑定就诊人,3改签,4充值成功
        $sms->sendCaptcha($mobile, 2);
        $updata['member_count'] = $res['member_count'] + 1;
        $user->up($where, $updata); // 更新就诊人数量
        $res = ['state' => 1, 'msg' => '添加就诊人成功'];
        return $res;
    }

    /**
     * 根据id 获取 就诊人信息
     */
    public function getMemberById($request)
    {
        $data = $this->getMemberInfoById($request['id']);
        if ($data) {
            $data = $data->toArray();
        }
        return ['state' => 1, 'msg' => 'ok', 'data' => $data];
    }

    /**
     * 获取档案信息
     */
    public function getMemberByInfo($request)
    {
        $where['id'] = $request['id'];
        $member = $this->getMemberById($where);
        $data = apiCurl('memberInfo', array('cardno' => $member['data']['cardno']));
    }

    /**
     * @param $request
     * @return bool|mixed
     */
    public function getMemberReport($request)
    {
        $where['id'] = $request['id'];
        $member = $this->getMemberById($where);
        $card = new Card();
        $card_info = $card->getOne(array('member_id' => $member['data']['id']));
        if ($card_info) {
            $card_info = $card_info->toArray();
        }
        $data = apiCurl('lisReport', array('m_id' => $member['data']['reffer_id'], 'u_id' => $member['data']['reffer_id'], 'cardno' => $card_info['card_no']));
        return $data;
    }

    /**
     * 获取缴费记录
     */
    public function getMemberCharge($request)
    {
        $member = $this->getMemberById(array('id' => $request['m_id']));
        if (Cache::get("list" . $request['m_id'])) {
            $res = Cache::get("list" . $request['m_id']);
        } else {
            $res = apiCurl('getVBL', $member['data']['card']['reffer_id']);
            if (isset($res['ret'])) {
                return ['state' => 1, 'msg' => "缴费记录为空"];
            }
            Cache::forever('list' . $request['m_id'], $res);
        }
        foreach ($res as $key => $v) {
            $res[$key]['time'] = date("Y-m-d", strtotime($v['VBL19']));
        }
        if (isset($_GET['page'])) {
            $_Page = $_GET['page'];
        } else {
            $_Page = 1;
        }
        $res = page_array(20, $_Page, $res, 0);
        return ['state' => 1, 'msg' => "ok", 'data' => $res, 'name' => $member['data']['name']];
    }

    /**
     * 获取病例模型
     */
    public function getVAQ($request)
    {
        $folder_path_for_images = public_path() . '/PDF/' . $request['m_id'] . '/' . $request['vid'];
        if (is_dir($folder_path_for_images)) {
            $filesnames = scandir($folder_path_for_images);
            if (is_array($filesnames)) {
                $file = [];
                foreach ($filesnames as $v) {
                    if ($v != '.' && $v != '..') {
                        $file[] = "/PDF/" . $request['m_id'] . '/' . $request['vid'] . "/" . $v;
                    }
                }
                $data['images'] = $file;
                return $data;
            }
        }
        if (!is_dir($folder_path_for_images)) {
            mkdir($folder_path_for_images);
        }
        $res = apiCurl("getVAR", $request['vid']);
        $PDF = new PDFLib();
        $url = "http://155m5k1578.iask.in:32292/"; // 接口url
        $pdf_file_path = $url . str_ireplace("E:", 'Z:', $res['URL']);
        $pdf = GrabImage($pdf_file_path, "");
        $PDF->setPdfPath($pdf_file_path);
        $PDF->setPdfPath($pdf);
        $PDF->setOutputPath($folder_path_for_images);
        $PDF->setImageFormat($PDF::$IMAGE_FORMAT_PNG);
        $PDF->setDPI(300);
        $PDF->setPageRange(1, $PDF->getNumberOfPages());
        $PDF->convert();
        $filesnames = scandir($folder_path_for_images);
        if (is_array($filesnames)) {
            $file = [];
            foreach ($filesnames as $v) {
                if ($v != '.' && $v != '..') {
                    $file[] = "/PDF/" . $request['m_id'] . '/' . $request['vid'] . "/" . $v;
                }
            }
            $data['images'] = $file;
            return $data;
        }
        return false;
    }

    public function getVAJ($request)
    {
        $res = apiCurl('getVAJ', array('tab' => $request['tab'], 'id' => $request['id'], 'time' => $request['time']));
        $newarr = array();
        if (empty($res[0])) {
            $newarr[] = $res;
        } else {
            $newarr = $res;
        }
        return array('data' => $newarr);
    }

    /**
     * 获取检验列表
     * @param $request
     * @return array
     */
    public function getListReport($request)
    {
        $member = $this->getMemberById(array('id' => $request['m_id']));
        $res = apiCurl('lisReport', $member['data']['card']['reffer_id']);
        if (empty($res[0])) {
            return ['state' => 0, 'msg' => "暂无检验数据"];
        }
        $allCateName = [];
        $cateNameArr = [];
        $arr = [];
        $key = 0;
        foreach ($res as $v) {
            $cateName['catename'] = $v['CateName'];
            $cateName['yqname'] = $v['仪器名称'];
            if (!in_array($cateName, $cateNameArr)) {
                $arr[] = $v;
                $cateNameArr[] = $cateName;
                $key++;
            }
            $allCateName[$key][] = $v;
        }
        // 写入缓存
        Cache::forever('allCateName' . $request['m_id'], $allCateName);
        return ['state' => 1, 'msg' => "ok", 'data' => $arr, 'name' => $member['data']['name']];
    }

    /**
     * 获取检验详情
     */
    public function ListReportInfo($request)
    {
//          从缓存里面读取
        $all_res = Cache::get("allCateName" . $request['m_id']);
        $member = $this->getMemberById(array('id' => $request['m_id']));
        $data['name'] = $member['data']['name'];
        $thisLisReport = $all_res[$request['item_id'] + 1];
        $res = ['state' => 1, 'msg' => "ok", 'name' => $data['name'], 'data' => $thisLisReport];
        return $res;
    }

    /**
     *  获取该用户的就诊记录
     */
    public function getAppoint($request)
    {
        $member = $this->getMemberById(array('id' => $request['m_id']));
        apiCurl('getVAC', array('id' => $member['data']['card']['reffer_id']));
    }

    /**
     * 获取病人基本信息
     * @param $request
     */
    public function getInptList($request)
    {
        $member = $this->getMemberById(array('id' => $request['m_id']));
        $newArr = [];
        if ($request['tab'] == 2) {
            $res1 = apiCurl('inptList', $member['data']['card']['reffer_id']);
            $tab = 2;
        } else {
            $res1 = apiCurl('getRegState', $member['data']['card']['reffer_id']);
            $tab = 1;
        }
        if (isset($res1['ret'])) {
            return ['state' => 1, 'msg' => '暂无记录'];
        }
        if (!isset($res1[0])) {
            $newarr[] = $res1;
        } else {
            $newarr = $res1;
        }
        $vajList = [];
        foreach ($newarr as $v) {
            if ($request['tab'] == 2) {
                $VACF = $v['VAE01'];
            } else {
                $VACF = $v['VAC01'];
            }
            $res = apiCurl('getVAJ', array("tab" => $tab, 'id' => $VACF, 'stime' => isset($v['VAE11']) ? $v['VAE11'] : 0, 'etime' => isset($v['VAE11']) ? $v['VAE11'] : 0));
            if (!empty($vajList)) {
                if (isset($res[0])) {
                    $vajList = array_merge($vajList, $res);
                } else {
                    if (isset($res['ret'])) {
                        if (!empty($res['ret']['data']['Data'])) {
                            $vajList = $res['ret']['data']['Data'];
                        }
                    } else {
                        $vajList[] = $res;
                    }
                }
            } else {
                if (isset($res['ret'])) {
                    if (!empty($res['ret']['data']['Data'])) {
                        $vajList = $res['ret']['data']['Data'];
                    }
                } else {
                    $vajList[] = $res;
                }
            }
        }
        $time = array();
        $arr = [];
        $key = 0;
        $count = 0;
        if ($request['tab'] == 2) {
            $vajList = $vajList[0];
        }
        // 归组分类
        foreach ($vajList as $k => $v) {
            $ex_time = explode(' ', $v['recdate']);
            if (!in_array($ex_time[0], $time)) {
                $time[] = $ex_time[0];
                if ($key != 0) {
                    $arr[$key]['countMoney'] = $count;
                }
                $count = 0;
                $key++;
            }
            $count += $v['VAJ38'];
            $arr[$key]['time'] = date("Y年m月d日", strtotime($ex_time[0]));
            $arr[$key]['data'][] = $v;
            if ($k == count($vajList) - 1) {
                $arr[$key]['countMoney'] = $count;
            }
        }
        if (empty($vajList)) {
            return ['state' => 1, 'msg' => "暂无数据清单", 'data' => []];
        }
        return ['state' => 1, 'msg' => "ok", 'data' => $arr, 'name' => $member['data']['name']];
    }

    /**
     * 获取每日基治疗信息
     */
    public function getDayList($request)
    {
        $res = apiCurl('getVAJ', array("tab" => $request['tab'], 'id' => $request['m_id'], 'stime' => $request['stime'], 'etime' => $request['etime']));
        return ajax_return($res);
    }

    /**
     * 获取检查列表
     * @param $request
     * @return array
     */
    public function risReportDetail($request)
    {
        $member = $this->getMemberById(array('id' => $request['m_id']));
        $resulte = apiCurl('risReportDetail', $member['data']['card']['reffer_id']);
        $res = [];
        if (isset($resulte['ret'])) {
            return ['state' => 0, 'msg' => '暂无记录'];
        }
        if (!isset($resulte[0])) {
            $res[] = $resulte;
        } else {
            $res = $resulte;
        }
        $imgUrl = "http://155m5k1578.iask.in:32292";
        foreach ($res as $key => $v) {
            $ary = parse_url($imgUrl . $v['vtPath']);
            $fileName = basename($ary['path']);
            $path = public_path() . '/vrimags/' . $request['m_id'];
            $res[$key]['vrimags'] = '/vrimags/' . $request['m_id'] . '/' . $fileName;
            if (!file_exists($path . '/' . $fileName)) {
                //下载图片到本地
                downloadFile($imgUrl . $v['vtPath'], $path);
            }
        }
        return ['state' => 1, 'msg' => "ok", 'data' => $res];
    }

    /**
     * 获取病例内容
     */
    public function getVAR($request)
    {
        $res = apiCurl("getVAR", $request['id']);
        return $res;
    }

    public function getVAF($request)
    {
        $member = $this->getMemberById(array('id' => $request['m_id']));
        //判断是否门诊病例  1.门诊  2.住院
        if ($request['tab'] == 1) {
            $res = apiCurl('getRegState', $member['data']['card']['reffer_id']);
        } else {
            $res = apiCurl('getVAE', $member['data']['card']['reffer_id']);
        }
        if (isset($res['ret'])) {
            return ['state' => 0, 'msg' => '暂无病历列表'];
        }
        $newarr = [];
        if (!isset($res[0])) {
            $newarr[] = $res;
        }
        if (empty($newarr)) {
            $data['data'] = [];
            $data['name'] = $member['data']['name'];
            return $data;
        }
        $arrList = '';
        foreach ($newarr as $v) {
            if ($request['tab'] == 1) {
                $VAA07 = $v['VAC01'];
            } else {
                $VAA07 = $v['VAE01'];
            }
            $result = apiCurl("getVAQ", array('m_id' => $member['data']['card']['reffer_id'], 'h_id' => $VAA07));
            if (isset($result['ret'])) {
                return ['state' => 0, 'msg' => '暂无病历列表'];
            }
            if (!empty($arrList)) {
                array_merge($arrList, $result);
            } else {
                $arrList = $result;
            }
        }
        $data['data'] = $arrList;
        $data['name'] = $member['data']['name'];
        return $data;
    }

    public function his_inpt_list($vaa01)
    {
        $data['vaa01'] = $vaa01;
        return $data;
    }

    public function his_get_reg_state($vaa01)
    {
        $data['vaa01'] = $vaa01;
        return $data;
    }

    /**
     * 编辑就诊人
     * @param $request
     * @return array
     */
    public function editMember($request)
    {
        $mobile = $request['mobile'];
        $relation = $request['relation'];
        $id_card = $request['id_card'];

        $data['name'] = $request['name'];
        $data['sex'] = $request['sex'];
        $data['birthday'] = $request['birthday'];
        $data['relation'] = $relation;
        $data['id_card'] = $id_card;
        $data['mobile'] = $mobile;
        $where['id'] = $request['id'];

        $mid = $this->up($where, $data);
        if (!$mid) {
            $res = ['state' => 0, 'msg' => '更新就诊人失败'];
            return $res;
        }
        $res = ['state' => 1, 'msg' => '更新就诊人成功'];
        return $res;
    }


    /*用户登记
    *参数说明：
    openid string 微信OpenID
    name string 姓名
    tel String 手机号
    sex int 性别1男2女0未知
    age int 年龄
    idno String(18) 身份证号码15/18
    type Int default 0 0自己1联系人
    sca01 int 编辑时需要提供，默认0
    *return
    Result int 1成功0失败
    Errmsg string 失败信息/错误原因
    SCA01 int SCA1.SCA01 CRM客户ID
    VAA01 int VAA1.VAA01 病人ID(暂未返回)
    */
    public function his_user_reg($params)
    {
        $data['openid'] = $params['openid'];
        $data['name'] = $params['name'];
        $data['tel'] = $params['mobile'];
        $data['sex'] = $params['sex'];
        $data['age'] = $params['age'];
        $data['idno'] = $params['id_card'];
        $data['type'] = isset($params['type']) ? $params['type'] : 0;
        $data['sca01'] = 0;
        return $data;
    }

    /**
     * 获取就诊id
     * @param $param
     * @return mixed
     */
    public function his_get_vac($param)
    {
        $data['vaa01'] = $param['id'];
        $data['timestart'] = $param['stime'];
        $data['timeend'] = $param['etime'];
        return $data;
    }

    /**
     * 获取his登记用户信息的编号
     * @param $cardno 手机号
     * @param $name 用户姓名
     * @return int 用户登记id sca01
     */
    public function his_get_user($params)
    {
        $data['cardno'] = $params['cardno'];
        $data['name'] = $params['name'];
        return $data;
    }

    public function his_get_vaj($param)
    {
        $data['acf01'] = $param['tab'];
        $data['vaa07'] = $param['id'];
        $data['bdate'] = $param['stime'] ? $param['stime'] : '';
        $data['edate'] = $param['etime'] ? $param['etime'] : '';
        return $data;
    }


    /**
     * 获取就诊人病例
     * @param $cardno
     * @return mixed
     */
    public function his_member_bill($cardno)
    {
        $data['cardno'] = $cardno;
        return $data;
    }

    /**
     * 获取病例列表
     * @param $mid
     * @return mixed
     */
    public function his_get_vaq($params)
    {
        $data['vaa01'] = $params['m_id'];
        $data['vaa07'] = $params['h_id'];
        return $data;
    }

    public function his_ris_report_detail($mid)
    {
        $data['vaa01'] = $mid;
        return $data;
    }

    /**
     * 获取会员信息
     */
    public function his_member_info($cardno)
    {
        $data['cardno'] = $cardno;
        return $data;
    }

    public function his_get_var($mid)
    {
        $data['vaq01'] = $mid;
        return $data;
    }


    /**
     * 获取会员检测报告
     */
    public function his_lis_report($param)
    {
        $data['vaa01'] = $param;
        $data['sca01'] = 0;
        $data['cardno'] = '';
        return $data;
    }

    public function his_get_vaf($mid)
    {
        $member = $this->getMemberById(array('id' => $mid));
        $data['acf01'] = 1;
        $data['vaf06'] = 400;
        return $data;
    }

    public function his_get_vbl($vaa01)
    {
        $data['vaa01'] = $vaa01;
        return $data;
    }

    public function delMember()
    {
        $where['id'] = request('id');
        $user = new \App\Models\User();
        $u_where['id'] = request('mid');
        $this->start();
        try {
            $user->dec($u_where, 'member_count', 1);
            $this->del($where);
            $card = new Card();
            $card->del(['member_id' => $where['id']]);
            $this->commit();
            return ['state' => 1, 'msg' => 'ok'];
        } catch (Exception $e) {
            $this->rollBack();
            return ['state' => 0, 'msg' => 'fail'];
        }
    }
}